// pages/addNote/addNote.js
Page({
  data: {
      title: '',
      array: ['日常生活', '学术', '人际交往'],
      area: 0,
      tag: '',
      text: '',
      imageCount: 0,
      images: []
  },
  handleTitleInput(e) {
      this.setData({
          title: e.detail.value
      });
  },
  handleCategoryChange(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value);
      this.setData({
          area: e.detail.value
      });
  },
  handleTagInput(e) {
      this.setData({
          tag: e.detail.value
      });
  },
  handleTextareaInput(e) {
      this.setData({
          text: e.detail.value
      });
  },
  chooseImage() {
      const that = this;
      wx.chooseImage({
          count: 4 - that.data.imageCount,
          success(res) {
              that.setData({
                  images: that.data.images.concat(res.tempFilePaths),
                  imageCount: that.data.imageCount + res.tempFilePaths.length
              });
          },
          fail(err) {
              console.error('选择图片失败:', err);
          }
      });
  },
  abandon() {
      wx.navigateBack({
        delta:1
      })
      wx.showToast({
          title: '已放弃',
          icon:'success'
      });
  },
  confirm() {
      const that = this;
      const { title, area, tag, text, images } = this.data;

      if (!title || !text) {
          wx.showToast({ title: '标题和内容不能为空', icon: 'none' });
          return;
      }

      wx.request({
          url: 'http://localhost:8848/Note/add',
          method: 'POST',
          header: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          data: {
              title: title,
              tag: tag,
              text: text,
              img: '', // 初始为空
              areaID: parseInt(area)
          },
          success(res) {
              if (res.statusCode === 200) {
                  const noteId = res.data.notenum; // 获取后端返回的 notenum
                  if (images.length === 0) {
                      wx.showToast({ title: '添加成功', icon: 'success' });
                      setTimeout(() => {
                        wx.navigateTo({ url: '/pages/area-life/area-life' });
                      }, 1500);
                      return;
                    };

                  // 上传图片并携带 noteId
                  let uploadPromises = images.map(image => {
                      console.log('上传文件路径:', image);
                      return new Promise((resolve, reject) => {
                          wx.uploadFile({
                              url: 'http://localhost:8848/Note/uploadImage',
                              filePath: image,
                              name: 'file',
                              formData: { noteId: noteId }, // 添加 noteId 参数
                              header: {
                                  // 去掉 Content-Type 设置，使用默认的 multipart/form-data
                                  'Authorization': 'Bearer ' + wx.getStorageSync('token')
                              },
                              success(res) {
                                  console.log('上传文件响应:', res);
                                  if (res.statusCode === 200) resolve();
                                  else {
                                      console.error('上传失败，状态码:', res.statusCode, '响应数据:', res.data);
                                      reject(new Error('上传失败'));
                                  }
                              },
                              fail: (err) => {
                                  console.error('上传失败，错误信息:', err);
                                  reject(err);
                              }
                          });
                      });
                  });

                  Promise.all(uploadPromises)
                     .then(() => {
                          wx.showToast({ title: '添加成功', icon: 'success' });
                          setTimeout(() => wx.navigateBack(), 1500);
                      })
                     .catch(err => {
                          console.error('上传失败:', err);
                          wx.showToast({ title: '图片上传失败', icon: 'none' });
                      });
              } else {
                  wx.showToast({ title: '失败：' + (res.data || '未知错误'), icon: 'none' });
              }
          },
          fail: err => {
              console.error('网络请求失败，错误信息:', err);
              wx.showToast({ title: '网络错误', icon: 'none' });
          }
      });
  }
});
  
     